package com.example.aicooking.service.imp;

import com.example.aicooking.entity.RefrigeratorFood;
import com.example.aicooking.entity.vo.RefrigeratorFoodVO;
import com.example.aicooking.mapper.RefrigeratorFoodMapper;
import com.example.aicooking.service.RefrigeratorFoodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class RefrigeratorFoodServiceImpl implements RefrigeratorFoodService {
    @Autowired
    private RefrigeratorFoodMapper refrigeratorFoodMapper;

    public List<RefrigeratorFoodVO> getFoodList(Long userId) {
        List<RefrigeratorFood> foods = refrigeratorFoodMapper.selectByUserId(userId);
        return foods.stream().map(food -> {
            RefrigeratorFoodVO vo = new RefrigeratorFoodVO();
            BeanUtils.copyProperties(food, vo);

            // 计算已保存时间（小时）
            long storedHours = Duration.between(food.getStorageTime(), LocalDateTime.now()).toHours();
            vo.setStoredHours((int) storedHours);

            // 设置保鲜时间展示文本
            int days = (int) (storedHours / 24);
            int remainingHours = (int) (storedHours % 24);

            if (days>0){
                vo.setStoredTimeText(days + "天" + remainingHours + "小时");
            }else {
                vo.setStoredTimeText( remainingHours + "小时");
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean deleteFood(Long id, Long userId) {
        // 先检查食材是否存在且属于该用户
        RefrigeratorFood food = refrigeratorFoodMapper.selectByIdAndUserId(id, userId);
        if (food == null) {
            log.warn("食材不存在或不属于用户, id={}, userId={}", id, userId);
            return false;
        }

        try {
            // 执行删除操作
            int result = refrigeratorFoodMapper.deleteByIdAndUserId(id, userId);
            if (result > 0) {
                log.info("成功删除食材, id={}, userId={}", id, userId);
                return true;
            } else {
                log.warn("删除食材失败, id={}, userId={}", id, userId);
                return false;
            }
        } catch (Exception e) {
            log.error("删除食材异常, id={}, userId={}", id, userId, e);
            throw new RuntimeException("删除食材失败", e);
        }
    }
}